<template>
    <div>
      <h3>通知</h3>
      <el-timeline :reverse="true">
        <el-timeline-item
          v-for="notification in notificationList"
          :key="notification.id"
          :type="notification.type==='system'?'primary':'success'"
          size="large"
          :icon="notification.type==='system'?'el-icon-more':'el-icon-bell'"
          :timestamp="notification.createdTime | dateFormat">
          {{notification.content}}
        </el-timeline-item>
      </el-timeline>
    </div>
</template>

<script>
export default {
  name: 'Notification',
  data () {
    return {
      notificationList: []
    }
  },
  filters: {
    dateFormat: function (value) {
      const date = new Date(value)
      // const y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let m = date.getMinutes()
      m = m < 10 ? '0' + m : m
      return MM + '-' + d + ' ' + h + ':' + m
    }
  },
  methods: {
    getNotification () {
      const userId = this.$store.getters.getCurrentUserId
      this.$axios.get('/notification', {
        params: { userId },
        headers: { Authorization: this.$store.state.jwt }
      })
        .then(response => {
          // 更新后端消息设为已读，同时更新vuex状态
          if (this.$store.state.hasNewMessage === 'yes') {
            this.$axios.post('/notification/update', {
              receiverId: this.$store.getters.getCurrentUserId
            }, {
              headers: { Authorization: this.$store.state.jwt }
            }).then(response => {
              this.$store.commit('set_new_message', 'no')
            })
          }
          this.$store.commit('set_new_message', 'no')
          // 调整显示内容
          const list = response.data.data
          list.forEach(value => {
            if (value.type === 'new_follower') {
              this.$axios.get('/users/' + value.relatedUserId).then(response => {
                value.content = '用户' + response.data.data.nickname + '关注了你'
              })
            } else if (value.type === 'system') {
              value.content = '[系统公告]' + value.content
            }
          })
          this.notificationList = list
        })
    }
  },
  mounted () {
    if (this.$store.state.loggedIn) {
      this.getNotification()
    }
  }
}
</script>

<style scoped>

</style>
